using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace DareMusicFixer
{
    public class ImageHelpers
    {
        public static byte[] Scale(Image img, float width, float height)
        {
            byte[] toReturn = null;

            if (img != null)
            {
                using (Bitmap bmPhoto = new Bitmap((int)width, (int)height, PixelFormat.Format24bppRgb))
                {
                    bmPhoto.SetResolution(img.HorizontalResolution, img.VerticalResolution);

                    using (Graphics g = Graphics.FromImage(bmPhoto))
                    {
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.ScaleTransform(width / img.Width, height / img.Height);
                        g.DrawImage(img, new Point(0, 0));
                        g.Flush();
                    }

                    toReturn = ImageToByteArray(bmPhoto);
                }
            }

            return toReturn;
        }

        public static byte[] ImageToByteArray(Image img)
        {
            byte[] toReturn = null;

            if (img != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    toReturn = ms.ToArray();
                }
            }

            return toReturn;
        }

        public static Image ByteArrayToImage(byte[] byteArray)
        {
            Image toReturn = null;

            if (byteArray != null && byteArray.Length != 0)
            {
                using (MemoryStream ms = new MemoryStream(byteArray))
                {
                    toReturn = Image.FromStream(ms);
                }
            }

            return toReturn;
        }

        public static float ImageSizeKB(long lengthOfByteArray)
        {
            return lengthOfByteArray * 1.0f / 1024.0f;
        }

        public static float ImageSizeKB(long lengthOfByteArray, int decimals)
        {
            return (float)Math.Round(ImageSizeKB(lengthOfByteArray));
        }
    }
}
